<template>
  <div class="app-container">
    <div>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:faultType:add']">添加</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
      </el-row>

      <el-table v-loading="loading" :data="list">
        <el-table-column label="编码" align="center" prop="code" />
        <el-table-column label="故障类型" align="center" prop="name" />
        <el-table-column label="是否启用" align="center" prop="enabled">
          <template slot-scope="scope">
            <div style="display:inline-flex;align-items:center;">
              <el-switch
                v-model="scope.row.enabled"
                :active-value="1"
                :inactive-value="0"
                @change="onToggleEnabled(scope.row,$event)"
              />
              <span style="margin-left:8px;color:#303133;">{{ scope.row.enabled===1?'启用':'禁用' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:faultType:edit']">编辑</el-button>
            <el-button
              size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:faultType:remove']"
              style="color: #f56c6c;"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹窗：新增/编辑故障类型 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="520px" append-to-body :close-on-click-modal="false" :show-close="false">
      <fault-type-form v-if="dialogVisible" :mode="dialogMode" :code="editCode" :disable-enabled="false" @success="onFormSuccess" @close="dialogVisible=false" />
    </el-dialog>
  </div>
</template>

<script>
import { listFaultType, delFaultType, updateFaultType } from '@/api/dict/faultType'
import FaultTypeForm from './components/FaultTypeForm.vue'
import { refreshDictionary } from '@/utils/dictionary'

export default {
  name: 'FaultType',
  components: { FaultTypeForm },
  computed: {},
  data(){
    return { loading:true, showSearch:true, list:[], queryParams:{ pageNum:1, pageSize:9999 }, dialogVisible:false, dialogMode:'create', editCode:'', currentEditingInUse:false, dialogTitle:'' }
  },
  async created(){ await this.getList() },
  watch:{},
  methods:{
    async getList(){
      this.loading=true
      const res = await listFaultType(this.queryParams)
      this.list=(res.rows||[]).map(it=>({
        ...it,
        enabled: (it.enabled===undefined||it.enabled===null) ? 1 : ((it.enabled===1||it.enabled==='1'||it.enabled===true)?1:0)
      }));
      this.loading=false
    },
    handleAdd(){ this.dialogMode='create'; this.editCode=''; this.dialogVisible=true },
    handleUpdate(row){ this.dialogMode='edit'; this.editCode=row.code; this.dialogVisible=true },
    handleDelete(row){
      const code = row.code
      this.$modal.confirm('确定删除编码为"'+code+'"的数据项？')
        .then(()=> delFaultType(code))
        .then(()=>{ this.getList(); this.$modal.msgSuccess('删除成功') })
        .catch(err => { if (err && err.response && err.response.data && err.response.data.msg) { this.$modal.msgError({ message: err.response.data.msg, duration: 2000 }) } })
    },
    onFormSuccess(){ this.dialogVisible=false; this.getList() },
    async onToggleEnabled(row,newVal){
      const original=row.enabled; row.enabled=newVal
      try {
        await updateFaultType({ code:row.code, enabled:Number(newVal) })
        this.$modal.msgSuccess({message:'状态已更新',duration:800});
        // 刷新字典缓存，确保其他页面使用最新的数据
        await refreshDictionary('faultTypes')
      } catch (error) {
        row.enabled=original
        // 显示后端返回的具体错误信息
        const errorMsg = error.response?.data?.msg || '更新失败'
        this.$modal.msgError({ message: errorMsg, duration: 2000 })
      }
    }
  }
}
</script>


